/**
 * 
 */
package com.dhcc.cdbp.query;

import static org.junit.Assert.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * 数字范围内搜索
 * @author 谢进军
 *
 */
public class NumericRangeQueryTest {
	private static final String fieldName = "contents";
	private static int value = 5;
	private static int min = 1;  
	private static int max = 9;
	Directory directory = null;
	@Before public void setUp() throws Exception {
		directory = new RAMDirectory();
		IndexWriterConfig iwc = new IndexWriterConfig(new StandardAnalyzer());
		iwc.setOpenMode(OpenMode.CREATE);
		IndexWriter writer = new IndexWriter(directory, iwc);
		Document document = new Document();
		document.add(new IntField(fieldName, value,Store.YES));
		writer.addDocument(document);
		assertEquals(1, writer.maxDoc());
		writer.close();
	}
	@Test public void test() throws IOException {
		List<Document> result = new ArrayList<>();
		IndexReader reader = DirectoryReader.open(directory);
		assertEquals(1, reader.maxDoc());
		IndexSearcher searcher = new IndexSearcher(reader);
		Query query = NumericRangeQuery.newIntRange(fieldName, min, max, true, true);
		TopDocs docs = searcher.search(query, 10);
		assertEquals(1, docs.totalHits);
		ScoreDoc[] hits = docs.scoreDocs;
		for (ScoreDoc doc : hits) {
			int docId = doc.doc;
			Document document = searcher.doc(docId);
			result.add(document);
		}
		
		for( Document document : result){
			System.out.println(document.toString());
		}
		reader.close();
		directory.close();
	}
	@After public void tearDown() throws Exception {
	}
}
